using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SheLife.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class HabitController : ControllerBase
    {
        private readonly IHabitService _habitService;

        public HabitController(IHabitService habitService)
        {
            _habitService = habitService;
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Habit>> GetHabit(int id)
        {
            var habit = await _habitService.GetHabitByIdAsync(id);
            if (habit == null)
            {
                return NotFound();
            }
            return habit;
        }

        [HttpGet("user/{userId}")]
        public async Task<ActionResult<IEnumerable<Habit>>> GetHabitsByUserId(int userId)
        {
            var habits = await _habitService.GetHabitsByUserIdAsync(userId);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/category/{category}")]
        public async Task<ActionResult<IEnumerable<Habit>>> GetHabitsByCategory(int userId, string category)
        {
            var habits = await _habitService.GetHabitsByCategoryAsync(userId, category);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/active")]
        public async Task<ActionResult<IEnumerable<Habit>>> GetActiveHabits(int userId)
        {
            var habits = await _habitService.GetActiveHabitsAsync(userId);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/withrecords")]
        public async Task<ActionResult<IEnumerable<Habit>>> GetHabitsWithRecords(int userId)
        {
            var habits = await _habitService.GetHabitsWithRecordsAsync(userId);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/stats")]
        public async Task<ActionResult<object>> GetHabitStats(int userId)
        {
            var stats = await _habitService.GetHabitStatsAsync(userId);
            return Ok(stats);
        }

        [HttpPost]
        public async Task<ActionResult<Habit>> CreateHabit(Habit habit)
        {
            var createdHabit = await _habitService.CreateHabitAsync(habit);
            return CreatedAtAction(nameof(GetHabit), new { id = createdHabit.Id }, createdHabit);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateHabit(int id, Habit habit)
        {
            if (id != habit.Id)
            {
                return BadRequest();
            }

            await _habitService.UpdateHabitAsync(habit);
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHabit(int id)
        {
            await _habitService.DeleteHabitAsync(id);
            return NoContent();
        }
    }
}